package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.constants.message.NewsAutoScanConstants;
import com.heima.model.common.constants.message.NewsUpOrDownConstants;
import com.heima.model.common.constants.message.PublishArticleConstants;
import com.heima.model.common.constants.wemedia.WemediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.dtos.WmNewsDTO;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${file.oss.web-site}")
    String webSite;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private WmUserMapper wmUserMapper;

    /**
     * 查询所有自媒体文章  (条件分页查询)
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {

        //参数校验
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //条件查询
        LambdaQueryWrapper<WmNews> wrapper = Wrappers.lambdaQuery();

        if (StringUtils.isNotBlank(dto.getKeyword())) {
            // 文章标题模糊查询
            wrapper.like(WmNews::getTitle, dto.getKeyword());
        }

        if (dto.getChannelId() != null) {
            // 频道id
            wrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }

        if (dto.getStatus() != null) {
            // 文章状态
            wrapper.eq(WmNews::getStatus, dto.getStatus());
        }

        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {

            wrapper.between(WmNews::getCreatedTime, dto.getBeginPubDate(), dto.getBeginPubDate());
//            // 发布时间 >= 开始时间
//            wrapper.ge(dto.getBeginPubDate() != null,WmNews::getPublishTime, dto.getBeginPubDate())
//                    //发布时间  <=结束时间
//            .le(dto.getEndPubDate()!=null,WmNews::getPublishTime, dto.getBeginPubDate());

        }

        // 当前自媒体人文章
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        wrapper.eq(WmNews::getUserId, user.getId());

        // 按照创建日期倒序
        wrapper.orderByDesc(WmNews::getCreatedTime);

        //分页查询
        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        //执行查询
        IPage<WmNews> wmNewsIPage = this.page(page, wrapper);

        //返回数据

        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), wmNewsIPage.getTotal(), wmNewsIPage.getRecords());

        //返回结果设置host  地址 为图片访问前缀
        result.setHost(webSite);


        return result;

    }


    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult submitNews(WmNewsDTO dto) {
        // 1. 检查参数  封装WmNews对象
        WmNews wmNews = parseDtoToWmNews(dto);
        // 2. 保存或修改文章
        saveOrUpdateWmNews(wmNews);
        // 3. 保存 文章内容 或 封面  和 素材的关联关系
        //   3.1 从文章内容中抽取所有的素材路径
        List<String> materialUrls = parseContentImages(wmNews.getContent());
        //   3.2 保存文章内容引用素材的关联关系
        if (!CollectionUtils.isEmpty(materialUrls)){
            saveRelativeInfo(materialUrls,wmNews,WemediaConstants.WM_CONTENT_REFERENCE);
        }
        //   3.3 保存封面引用素材的关联关系
        saveRelativeInfoForCover(materialUrls,wmNews,dto);

        // 4. 发送MQ消息，触发异步的自动审核
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE,wmNews.getId());
        log.info("成功发送文章自动审核消息   目的队列:{}   文章id:{}",NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE,wmNews.getId());
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1 参数检查
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 执行查询
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3 返回结果
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }

    /**
     * 保存文章封面和素材的关联关系
     * @param materialUrls
     * @param wmNews
     * @param dto
     */
    private void saveRelativeInfoForCover(List<String> materialUrls, WmNews wmNews, WmNewsDTO dto) {
        List<String> images = dto.getImages();
        //              判断前端传入type是否为 -1
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            //  需要自动生成封面  规则
            int size = materialUrls.size();
            if(size == 0){
                //    - 内容中没有图片，则为无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }else if(size <= 2){
                //    - 内容图片的个数小于等于2  则为单图截图一张图
                images = materialUrls.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            }else {
                //    - 内容图片大于2，则为多图，截图三张图
                images = materialUrls.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            }
            if(!CollectionUtils.isEmpty(images)){
                wmNews.setImages(imagesToStr(images));
            }
            // 修改文章
            this.updateById(wmNews);
        }
        if(!CollectionUtils.isEmpty(images)){
            images = images.stream().map(url -> url.replaceAll(webSite,"")).collect(Collectors.toList());
            // 调用保存关联关系方法
            saveRelativeInfo(images,wmNews,WemediaConstants.WM_IMAGE_REFERENCE);
        }
    }

    /**
     * 保存素材和文章关联关系方法
     * @param materialUrls  素材的路径List
     * @param wmNews    文章
     * @param type  引用类型 0  内容引用   1   封面引用
     */
    private void saveRelativeInfo(List<String> materialUrls, WmNews wmNews, Short type) {
        // 1. 先根据素材路径集合  查询素材表 得到对应的id集合
//        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(
//                Wrappers.<WmMaterial>lambdaQuery()
//                        .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId())
//                        .in(WmMaterial::getUrl, materialUrls)
//                        // 只返回ID字段的值
//                        .select(WmMaterial::getId)
//        );
        List<Integer> ids = wmMaterialMapper.selectRelationsIds(materialUrls, WmThreadLocalUtils.getUser().getId());
        // 2. 判断id集合的数量 是否  等于 素材路径集合的数量， 不等于提示素材缺失
        if(ids.size() < materialUrls.size()){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"素材缺失");
        }
        // 3. 批量的插入关联关系
//        for (WmMaterial wmMaterial : wmMaterials) {
//            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
//            wmNewsMaterial.setMaterialId(wmMaterial.getId());
//            wmNewsMaterial.setNewsId(wmNews.getId());
//            wmNewsMaterial.setType(type);
//            wmNewsMaterialMapper.insert(wmNewsMaterial);
//        }
        wmNewsMaterialMapper.saveRelations(ids,wmNews.getId(),type);
    }

    /**
     * 提取出内容中 锁涉及的素材路径
     * @param content
     * @return
     */
    private List<String> parseContentImages(String content) {
        List<Map> mapList = JSON.parseArray(content, Map.class);
        return mapList.stream() // 创建流
                // 集合中 找到所有 type 为 image的map
                .filter(x -> "image".equals(x.get("type")))
                //  获取map的value字段值 得到路径
                .map(x -> String.valueOf(x.get("value")))
                //  替换掉路径的前缀
                .map(url -> url.replaceAll(webSite,""))
                //  去除重复的素材
                .distinct()
                // 将得到的素材返回路径集合
                .collect(Collectors.toList());
    }

    private void saveOrUpdateWmNews(WmNews wmNews) {
        //   2.1 wmNews信息补全(创建时间 上下架  发表用户id)
        wmNews.setCreatedTime(new Date());
        // 文章状态 9
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);
        //   2.2 判断id是否为空，
        if(wmNews.getId()==null){
//            为空保存wmNews
            this.save(wmNews);
        }else {
            //   2.3 如果不为空 修改wmNews 修改前要先将 文章和素材的关联关系删除
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            this.updateById(wmNews);
        }
    }

    private WmNews parseDtoToWmNews(WmNewsDTO dto) {
        //   1.1 检查内容  标题   是否登陆
        if (StringUtils.isBlank(dto.getTitle())||StringUtils.isBlank(dto.getContent())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章的标题和内容不能为空");
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"请先登陆");
        }
        //   1.2 dto拷贝属性wmNews
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        //   1.3 type:如果type为-1 暂时将wmNews中的type设置为null
        if(WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())){
            wmNews.setType(null);
        }
        //   1.4 dto中的images是list  wmNews的images是字符串
        if(!CollectionUtils.isEmpty(dto.getImages())){
            wmNews.setImages(imagesToStr(dto.getImages()));
        }
        //  1.5 补全id
        wmNews.setUserId(user.getId());
        return wmNews;
    }

    /**
     * 将字符串集合  转为  字符串用逗号拼接
     * @param images  [url1.jpg,url2.jpg]
     * @return
     */
    private String imagesToStr(List<String> images) {
        return images.stream() // 创建流对象
                // 替换路径中的访问前缀
                .map(url -> url.replaceAll(webSite,""))
                // 将字符串 使用逗号拼接
                .collect(Collectors.joining(","));
    }



    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult delNews(Integer id) {
        //校验参数
        if (id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章id不能为空");
        }
        //根据id查询文章
        WmNews wmNews = this.getById(id);

        if (wmNews==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }

        //判断文章状态  status ==9  enable==1
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode()) && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已发布，不能删除");
        }

        //去除素材和文章的关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
        //删除文章
        removeById(wmNews.getId());


        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        //1.检查参数
        if(dto == null || dto.getId() == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Short enable = dto.getEnable();
        if(enable == null ||
                (!WemediaConstants.WM_NEWS_UP.equals(enable)&&!WemediaConstants.WM_NEWS_DOWN.equals(enable))){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"上下架状态错误");
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.判断文章是否发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章不是发布状态，不能上下架");
        }
        //4.修改文章状态，同步到app端（后期做）TODO
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId())
                .set(WmNews::getEnable,dto.getEnable()));

        //5. 上下架发送消息通知  用于同步article 及 elasticsearch
        //5. 上下架发送消息通知  用于同步article 及 elasticsearch
        if (wmNews.getArticleId()!=null) {
            if(enable.equals(WemediaConstants.WM_NEWS_UP)){
                // 上架消息
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY,wmNews.getArticleId());
            }else {
                // 下架消息
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY,wmNews.getArticleId());
            }
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询文章列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(NewsAuthDTO dto) {
        //1.检查参数
        dto.checkParam();
        //记录当前页
        int currentPage = dto.getPage();
        //设置起始页
        dto.setPage((dto.getPage()-1)*dto.getSize());

        if(StringUtils.isNotBlank(dto.getTitle())){
            //  concat(%,?,%)
            dto.setTitle("%"+dto.getTitle()+"%");
        }

        //2.分页查询
        List<WmNewsVO> wmNewsVoList = wmNewsMapper.findListAndPage(dto);
        //统计多少条数据
        long count = wmNewsMapper.findListCount(dto);

        //3.结果返回
        ResponseResult result = new PageResponseResult(currentPage, dto.getSize(), count, wmNewsVoList);
        result.setHost(webSite);
        return result;
    }


    /**
     * 查询文章详情
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //1参数检查
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.查询作者
        WmUser wmUser = null;
        if(wmNews.getUserId() != null){
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }

        //4.封装vo信息返回
        WmNewsVO wmNewsVo = new WmNewsVO();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        if(wmUser != null){
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(webSite);
        return responseResult;
    }


    /**
     * 自媒体文章人工审核
     * @param status 2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDTO dto) {
        //1.参数检查
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 检查文章状态 不能为9  已发布
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章已发布");
        }
        //3.修改文章状态
        wmNews.setStatus(status);
        if(StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);

        //  通知定时发布文章
        // 发布时间
        long publishTime = wmNews.getPublishTime().getTime();
        // 当前时间
        long nowTime = new Date().getTime();
        long remainTime = publishTime - nowTime;
        // 发布文章
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE
                , PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                , wmNews.getId()
                , (message)->{                              // 延时消息 必设置
                    message.getMessageProperties().setHeader("x-delay",remainTime<=0?0:remainTime);
                    return message;
                }
        );
        log.info("立即发布文章通知成功发送，文章id : {}", wmNews.getId());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
